package system

import (
	"context"
	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gtime"
	"server/internal/dao"
	"server/internal/model"
	"server/internal/model/do"
	"server/internal/model/entity"
	"server/internal/service"
)

type sSystemConfigCategory struct {
}

func init() {
	service.RegisterSystemConfigCategory(&sSystemConfigCategory{})
}

func (s *sSystemConfigCategory) Create(ctx context.Context, in model.SystemConfigCategoryCreateInput) (id int64, err error) {
	id, err = dao.SystemConfigCategory.Ctx(ctx).Data(do.SystemConfigCategory{
		Name:      in.Name,
		Remark:    in.Remark,
		CreatedBy: service.SystemLogin().GetAdminID(ctx),
	}).InsertAndGetId()
	if err != nil {
		return 0, err
	}
	return id, nil
}

func (s *sSystemConfigCategory) GetOneByID(ctx context.Context, id int64) (data *entity.SystemConfigCategory, err error) {
	data = new(entity.SystemConfigCategory)
	err = dao.SystemConfigCategory.Ctx(ctx).Where(do.SystemConfigCategory{Id: id}).Scan(data)
	if err != nil {
		return nil, err
	}
	return data, nil
}

func (s *sSystemConfigCategory) UpdateByID(ctx context.Context, id int64, in model.SystemConfigCategoryUpdateInput) (rows int64, err error) {
	rows, err = dao.SystemConfigCategory.Ctx(ctx).Where(do.SystemConfigCategory{Id: id}).Data(do.SystemConfigCategory{
		Name:      in.Name,
		Remark:    in.Remark,
		UpdatedBy: service.SystemLogin().GetAdminID(ctx),
	}).UpdateAndGetAffected()
	if err != nil {
		return 0, err
	}
	return rows, nil
}

func (s *sSystemConfigCategory) DeleteByID(ctx context.Context, id int64) (rows int64, err error) {
	rows, err = dao.SystemConfigCategory.Ctx(ctx).Where(do.SystemConfigCategory{Id: id}).Data(do.SystemConfigCategory{
		DeletedAt: gtime.Now(),
		DeletedBy: service.SystemLogin().GetAdminID(ctx),
	}).UpdateAndGetAffected()
	if err != nil {
		return 0, err
	}
	return rows, nil
}

func (s *sSystemConfigCategory) List(ctx context.Context, in model.SystemConfigCategoryListInput) (list []model.SystemConfigCategoryListItem, total int, err error) {
	list = make([]model.SystemConfigCategoryListItem, 0)
	where := g.Map{}
	if len(in.Name) > 0 {
		where["name like ?"] = "%" + in.Name + "%"
	}
	err = dao.SystemConfigCategory.Ctx(ctx).Where(where).OrderAsc("id").Page(in.Page, in.PageSize).ScanAndCount(&list, &total, true)
	if err != nil {
		return
	}

	// 创建人
	err = dao.SystemUser.Ctx(ctx).As("u").Fields("u.*").
		WhereIn("u.id", gdb.ListItemValuesUnique(list, "CreatedBy")).
		ScanList(&list, "CreatedAdmin", "id:created_by")
	if err != nil {
		return
	}

	// 更新人
	err = dao.SystemUser.Ctx(ctx).As("u").Fields("u.*").
		WhereIn("u.id", gdb.ListItemValuesUnique(list, "UpdatedBy")).
		ScanList(&list, "UpdatedAdmin", "id:updated_by")
	if err != nil {
		return
	}

	return list, total, nil
}
